<template>
  <div class="chat-page">
    <div class="container">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="header-left">
          <el-button @click="handleBack" :icon="ArrowLeft" circle size="small" />
          <div class="contact-info">
            <div class="contact-avatar">
              <el-image
                :src="contactInfo?.avatar || '/default-avatar.jpg'"
                fit="cover"
                class="avatar"
              />
              <div 
                v-if="contactInfo?.isOnline" 
                class="online-indicator"
                :class="{ 'online': contactInfo.isOnline }"
              ></div>
            </div>
            <div class="contact-details">
              <h3>{{ contactInfo?.name || '客服' }}</h3>
              <p class="contact-status">
                {{ getContactStatus() }}
              </p>
            </div>
          </div>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleAction" trigger="click">
            <el-button :icon="MoreFilled" circle size="small" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile" :icon="User">
                  查看资料
                </el-dropdown-item>
                <el-dropdown-item command="clear" :icon="Delete">
                  清空聊天记录
                </el-dropdown-item>
                <el-dropdown-item command="report" :icon="Warning" divided>
                  举报
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 快捷操作栏 -->
      <div class="quick-actions" v-if="relatedOrder">
        <el-card class="order-card" @click="viewOrder">
          <div class="order-info">
            <el-icon><Document /></el-icon>
            <div class="order-details">
              <span class="order-title">订单 {{ relatedOrder.orderNumber }}</span>
              <span class="order-status">{{ relatedOrder.statusText }}</span>
            </div>
          </div>
          <el-icon class="arrow-icon"><ArrowRight /></el-icon>
        </el-card>
      </div>

      <!-- 聊天区域 -->
      <div class="chat-container" ref="chatContainer">
        <div class="message-list" v-loading="loading">
          <!-- 日期分隔符 -->
          <div 
            v-for="(message, index) in messages" 
            :key="message.id"
          >
            <div 
              v-if="shouldShowDateSeparator(message, index)"
              class="date-separator"
            >
              <span>{{ formatDate(message.timestamp) }}</span>
            </div>

            <!-- 消息项 -->
            <div 
              class="message-item"
              :class="{ 
                'own-message': message.senderId === currentUserId,
                'other-message': message.senderId !== currentUserId
              }"
            >
              <div class="message-content">
                <div class="message-avatar" v-if="message.senderId !== currentUserId">
                  <el-image
                    :src="message.senderAvatar || '/default-avatar.jpg'"
                    fit="cover"
                    class="avatar"
                  />
                </div>

                <div class="message-bubble">
                  <!-- 文本消息 -->
                  <div 
                    v-if="message.type === 'text'"
                    class="text-message"
                    v-html="formatTextMessage(message.content)"
                  ></div>

                  <!-- 图片消息 -->
                  <div 
                    v-else-if="message.type === 'image'"
                    class="image-message"
                    @click="previewImage(message.content)"
                  >
                    <el-image
                      :src="message.content"
                      fit="cover"
                      class="message-image"
                      :preview-src-list="[message.content]"
                    />
                  </div>

                  <!-- 文件消息 -->
                  <div 
                    v-else-if="message.type === 'file'"
                    class="file-message"
                    @click="downloadFile(message.content)"
                  >
                    <el-icon><Document /></el-icon>
                    <div class="file-info">
                      <span class="file-name">{{ message.content.name }}</span>
                      <span class="file-size">{{ formatFileSize(message.content.size) }}</span>
                    </div>
                  </div>

                  <!-- 系统消息 -->
                  <div 
                    v-else-if="message.type === 'system'"
                    class="system-message"
                  >
                    {{ message.content }}
                  </div>

                  <!-- 消息状态 -->
                  <div class="message-status" v-if="message.senderId === currentUserId">
                    <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                    <el-icon 
                      v-if="message.status === 'sending'" 
                      class="status-icon sending"
                      color="#999"
                    >
                      <Loading />
                    </el-icon>
                    <el-icon 
                      v-else-if="message.status === 'sent'" 
                      class="status-icon sent"
                      color="#999"
                    >
                      <Check />
                    </el-icon>
                    <el-icon 
                      v-else-if="message.status === 'read'" 
                      class="status-icon read"
                      color="#409eff"
                    >
                      <Check />
                    </el-icon>
                    <el-icon 
                      v-else-if="message.status === 'failed'" 
                      class="status-icon failed"
                      color="#f56c6c"
                    >
                      <Close />
                    </el-icon>
                  </div>
                  <div class="message-time-other" v-else>
                    {{ formatTime(message.timestamp) }}
                  </div>
                </div>

                <div class="message-avatar" v-if="message.senderId === currentUserId">
                  <el-image
                    :src="currentUserAvatar || '/default-avatar.jpg'"
                    fit="cover"
                    class="avatar"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 正在输入指示器 -->
          <div v-if="isTyping" class="typing-indicator">
            <div class="typing-content">
              <div class="typing-avatar">
                <el-image
                  :src="contactInfo?.avatar || '/default-avatar.jpg'"
                  fit="cover"
                  class="avatar"
                />
              </div>
              <div class="typing-bubble">
                <div class="typing-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-toolbar">
          <el-upload
            :action="uploadAction"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleImageUpload"
            accept="image/*"
            class="upload-btn"
          >
            <el-button :icon="Picture" circle size="small" />
          </el-upload>

          <el-upload
            :action="uploadAction"
            :show-file-list="false"
            :before-upload="beforeFileUpload"
            :on-success="handleFileUpload"
            class="upload-btn"
          >
            <el-button :icon="Paperclip" circle size="small" />
          </el-upload>

          <el-button 
            v-if="contactInfo?.type === 'merchant'"
            @click="showQuickReplies = !showQuickReplies"
            :icon="ChatLineRound"
            circle 
            size="small"
          />
        </div>

        <div class="input-container">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            resize="none"
            placeholder="输入消息..."
            @keydown.enter.exact.prevent="sendMessage"
            @keydown.enter.shift.exact="handleNewLine"
            @input="handleTyping"
            @blur="handleStopTyping"
            ref="messageInput"
            maxlength="1000"
            show-word-limit
          />
          <el-button
            type="primary"
            @click="sendMessage"
            :disabled="!inputMessage.trim()"
            :loading="sending"
            class="send-btn"
          >
            发送
          </el-button>
        </div>

        <!-- 快捷回复 -->
        <div v-if="showQuickReplies" class="quick-replies">
          <h4>快捷回复</h4>
          <div class="reply-buttons">
            <el-button
              v-for="reply in quickReplies"
              :key="reply.id"
              size="small"
              @click="selectQuickReply(reply.content)"
            >
              {{ reply.content }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="previewImages"
      :initial-index="currentImageIndex"
      @close="showImageViewer = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  MoreFilled,
  User,
  Delete,
  Warning,
  Document,
  ArrowRight,
  Loading,
  Check,
  Close,
  Picture,
  Paperclip,
  ChatLineRound
} from '@element-plus/icons-vue'
import { chatApi, orderApi, uploadApi } from '@/services/api'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 数据定义
const loading = ref(true)
const sending = ref(false)
const messages = ref([])
const inputMessage = ref('')
const contactInfo = ref(null)
const relatedOrder = ref(null)
const isTyping = ref(false)
const showQuickReplies = ref(false)
const showImageViewer = ref(false)
const previewImages = ref([])
const currentImageIndex = ref(0)
const chatContainer = ref(null)
const messageInput = ref(null)

// WebSocket连接
let websocket = null
let typingTimer = null

// 上传配置
const uploadAction = ref('/api/upload/image')

// 当前用户信息
const currentUserId = computed(() => userStore.user?.id || 'user-1')
const currentUserAvatar = computed(() => userStore.user?.avatar)

// 快捷回复模板
const quickReplies = ref([
  { id: 1, content: '您好，有什么可以帮助您的吗？' },
  { id: 2, content: '请稍等，我马上为您处理。' },
  { id: 3, content: '感谢您的咨询，还有其他问题吗？' },
  { id: 4, content: '服务已安排，请保持电话畅通。' },
  { id: 5, content: '订单正在处理中，请耐心等待。' }
])

// 生命周期
onMounted(() => {
  const merchantId = route.params.merchantId
  const orderId = route.query.orderId
  
  if (merchantId) {
    initChat(merchantId, orderId)
    connectWebSocket(merchantId)
  }
})

onUnmounted(() => {
  if (websocket) {
    websocket.close()
  }
  if (typingTimer) {
    clearTimeout(typingTimer)
  }
})

// 方法定义
const initChat = async (merchantId, orderId) => {
  try {
    loading.value = true
    
    // 获取联系人信息
    const contactResponse = await chatApi.getContactInfo(merchantId)
    contactInfo.value = contactResponse.data
    
    // 获取聊天记录
    const messagesResponse = await chatApi.getChatMessages(merchantId)
    messages.value = messagesResponse.data || []
    
    // 获取相关订单信息
    if (orderId) {
      const orderResponse = await orderApi.getOrderDetail(orderId)
      relatedOrder.value = orderResponse.data
    }
    
    scrollToBottom()
  } catch (error) {
    console.error('初始化聊天失败:', error)
    
    // 使用模拟数据
    contactInfo.value = {
      id: merchantId,
      name: merchantId === 'service' ? '客服中心' : '专业洗护店',
      avatar: '/default-merchant.jpg',
      type: merchantId === 'service' ? 'service' : 'merchant',
      isOnline: true,
      lastSeen: new Date()
    }
    
    messages.value = [
      {
        id: 1,
        senderId: merchantId,
        senderAvatar: '/default-merchant.jpg',
        type: 'text',
        content: '您好！欢迎咨询，有什么可以帮助您的吗？',
        timestamp: new Date(Date.now() - 300000),
        status: 'read'
      },
      {
        id: 2,
        senderId: currentUserId.value,
        type: 'text',
        content: '你好，我想了解一下订单进度',
        timestamp: new Date(Date.now() - 240000),
        status: 'read'
      },
      {
        id: 3,
        senderId: merchantId,
        senderAvatar: '/default-merchant.jpg',
        type: 'text',
        content: '好的，请提供您的订单号，我来帮您查询。',
        timestamp: new Date(Date.now() - 180000),
        status: 'read'
      }
    ]
    
    if (orderId) {
      relatedOrder.value = {
        id: orderId,
        orderNumber: `202412280${orderId.toString().padStart(3, '0')}`,
        statusText: '服务中'
      }
    }
    
    ElMessage.error('获取聊天信息失败，显示模拟数据')
  } finally {
    loading.value = false
  }
}

const connectWebSocket = (merchantId) => {
  try {
    const wsUrl = `ws://localhost:3000/chat/${merchantId}`
    websocket = new WebSocket(wsUrl)
    
    websocket.onopen = () => {
      console.log('WebSocket连接已建立')
    }
    
    websocket.onmessage = (event) => {
      const data = JSON.parse(event.data)
      handleWebSocketMessage(data)
    }
    
    websocket.onclose = () => {
      console.log('WebSocket连接已关闭')
      // 尝试重连
      setTimeout(() => {
        if (!websocket || websocket.readyState === WebSocket.CLOSED) {
          connectWebSocket(merchantId)
        }
      }, 3000)
    }
    
    websocket.onerror = (error) => {
      console.error('WebSocket错误:', error)
    }
  } catch (error) {
    console.error('WebSocket连接失败:', error)
  }
}

const handleWebSocketMessage = (data) => {
  switch (data.type) {
    case 'message':
      messages.value.push(data.message)
      scrollToBottom()
      break
    case 'typing':
      isTyping.value = data.isTyping
      if (data.isTyping) {
        scrollToBottom()
      }
      break
    case 'read':
      markMessagesAsRead(data.messageIds)
      break
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || sending.value) return
  
  const messageContent = inputMessage.value.trim()
  inputMessage.value = ''
  sending.value = true
  
  const tempMessage = {
    id: Date.now(),
    senderId: currentUserId.value,
    type: 'text',
    content: messageContent,
    timestamp: new Date(),
    status: 'sending'
  }
  
  messages.value.push(tempMessage)
  scrollToBottom()
  
  try {
    const response = await chatApi.sendMessage({
      receiverId: route.params.merchantId,
      type: 'text',
      content: messageContent
    })
    
    // 更新消息状态
    const messageIndex = messages.value.findIndex(m => m.id === tempMessage.id)
    if (messageIndex > -1) {
      messages.value[messageIndex] = {
        ...tempMessage,
        id: response.data.id,
        status: 'sent'
      }
    }
    
    // 通过WebSocket发送
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send(JSON.stringify({
        type: 'message',
        message: tempMessage
      }))
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    // 更新消息状态为失败
    const messageIndex = messages.value.findIndex(m => m.id === tempMessage.id)
    if (messageIndex > -1) {
      messages.value[messageIndex].status = 'failed'
    }
    ElMessage.error('消息发送失败')
  } finally {
    sending.value = false
  }
}

const handleTyping = () => {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.send(JSON.stringify({
      type: 'typing',
      isTyping: true
    }))
  }
  
  // 清除之前的定时器
  if (typingTimer) {
    clearTimeout(typingTimer)
  }
  
  // 设置新的定时器，2秒后停止输入状态
  typingTimer = setTimeout(() => {
    handleStopTyping()
  }, 2000)
}

const handleStopTyping = () => {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.send(JSON.stringify({
      type: 'typing',
      isTyping: false
    }))
  }
}

const handleNewLine = () => {
  inputMessage.value += '\n'
}

const selectQuickReply = (content) => {
  inputMessage.value = content
  showQuickReplies.value = false
  nextTick(() => {
    messageInput.value?.focus()
  })
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const beforeFileUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

const handleImageUpload = (response, file) => {
  const imageMessage = {
    id: Date.now(),
    senderId: currentUserId.value,
    type: 'image',
    content: response.url || URL.createObjectURL(file.raw),
    timestamp: new Date(),
    status: 'sent'
  }
  
  messages.value.push(imageMessage)
  scrollToBottom()
}

const handleFileUpload = (response, file) => {
  const fileMessage = {
    id: Date.now(),
    senderId: currentUserId.value,
    type: 'file',
    content: {
      name: file.name,
      size: file.size,
      url: response.url || URL.createObjectURL(file.raw)
    },
    timestamp: new Date(),
    status: 'sent'
  }
  
  messages.value.push(fileMessage)
  scrollToBottom()
}

const previewImage = (imageSrc) => {
  previewImages.value = [imageSrc]
  currentImageIndex.value = 0
  showImageViewer.value = true
}

const downloadFile = (fileInfo) => {
  const link = document.createElement('a')
  link.href = fileInfo.url
  link.download = fileInfo.name
  link.click()
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

const shouldShowDateSeparator = (message, index) => {
  if (index === 0) return true
  
  const currentDate = dayjs(message.timestamp).format('YYYY-MM-DD')
  const prevDate = dayjs(messages.value[index - 1].timestamp).format('YYYY-MM-DD')
  
  return currentDate !== prevDate
}

const markMessagesAsRead = (messageIds) => {
  messageIds.forEach(id => {
    const message = messages.value.find(m => m.id === id)
    if (message && message.senderId === currentUserId.value) {
      message.status = 'read'
    }
  })
}

const handleBack = () => {
  router.back()
}

const handleAction = (command) => {
  switch (command) {
    case 'profile':
      if (contactInfo.value?.type === 'merchant') {
        router.push(`/merchants/${contactInfo.value.id}`)
      } else {
        ElMessage.info('查看客服资料功能开发中')
      }
      break
    case 'clear':
      clearChatHistory()
      break
    case 'report':
      ElMessage.info('举报功能开发中')
      break
  }
}

const clearChatHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空聊天记录吗？此操作无法撤销。',
      '清空聊天记录',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    messages.value = []
    ElMessage.success('聊天记录已清空')
  } catch (error) {
    // 用户取消
  }
}

const viewOrder = () => {
  if (relatedOrder.value) {
    router.push(`/orders/${relatedOrder.value.id}`)
  }
}

const getContactStatus = () => {
  if (!contactInfo.value) return ''
  
  if (contactInfo.value.type === 'service') {
    return '客服在线，随时为您服务'
  }
  
  if (contactInfo.value.isOnline) {
    return '在线'
  } else {
    return `最后在线：${formatTime(contactInfo.value.lastSeen)}`
  }
}

const formatTextMessage = (content) => {
  // 处理换行
  return content.replace(/\n/g, '<br>')
}

const formatTime = (date) => {
  return dayjs(date).format('HH:mm')
}

const formatDate = (date) => {
  const today = dayjs()
  const messageDate = dayjs(date)
  
  if (messageDate.isSame(today, 'day')) {
    return '今天'
  } else if (messageDate.isSame(today.subtract(1, 'day'), 'day')) {
    return '昨天'
  } else if (messageDate.isSame(today, 'year')) {
    return messageDate.format('MM月DD日')
  } else {
    return messageDate.format('YYYY年MM月DD日')
  }
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style lang="scss" scoped>
.chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 800px;
  margin: 0 auto;
  background: white;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: white;

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .contact-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .contact-avatar {
        position: relative;

        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }

        .online-indicator {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 12px;
          height: 12px;
          border-radius: 50%;
          border: 2px solid white;

          &.online {
            background-color: #67c23a;
          }
        }
      }

      .contact-details {
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }

        .contact-status {
          margin: 0;
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

.quick-actions {
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;

  .order-card {
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
    }

    :deep(.el-card__body) {
      padding: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .order-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .order-details {
        display: flex;
        flex-direction: column;

        .order-title {
          font-weight: 500;
          color: #333;
        }

        .order-status {
          font-size: 12px;
          color: #409eff;
        }
      }
    }

    .arrow-icon {
      color: #c0c4cc;
    }
  }
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f5f7fa;

  .message-list {
    min-height: 100%;
  }

  .date-separator {
    text-align: center;
    margin: 20px 0;

    span {
      background: rgba(0, 0, 0, 0.1);
      color: #666;
      padding: 4px 12px;
      border-radius: 12px;
      font-size: 12px;
    }
  }

  .message-item {
    margin-bottom: 16px;

    &.own-message {
      .message-content {
        justify-content: flex-end;

        .message-bubble {
          background: #409eff;
          color: white;
          margin-left: 60px;
        }
      }
    }

    &.other-message {
      .message-content {
        justify-content: flex-start;

        .message-bubble {
          background: white;
          color: #333;
          margin-right: 60px;
        }
      }
    }

    .message-content {
      display: flex;
      align-items: flex-end;
      gap: 8px;

      .message-avatar {
        .avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
        }
      }

      .message-bubble {
        max-width: 70%;
        padding: 10px 14px;
        border-radius: 18px;
        position: relative;
        word-break: break-word;

        .text-message {
          line-height: 1.4;
        }

        .image-message {
          .message-image {
            max-width: 200px;
            max-height: 200px;
            border-radius: 8px;
            cursor: pointer;
          }
        }

        .file-message {
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          padding: 8px;
          border: 1px solid #e4e7ed;
          border-radius: 8px;

          .file-info {
            display: flex;
            flex-direction: column;

            .file-name {
              font-weight: 500;
            }

            .file-size {
              font-size: 12px;
              color: #999;
            }
          }
        }

        .system-message {
          font-style: italic;
          opacity: 0.8;
        }

        .message-status {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 4px;
          margin-top: 4px;

          .message-time {
            font-size: 10px;
            opacity: 0.7;
          }

          .status-icon {
            font-size: 12px;

            &.sending {
              animation: rotating 1s linear infinite;
            }
          }
        }

        .message-time-other {
          margin-top: 4px;
          font-size: 10px;
          opacity: 0.7;
        }
      }
    }
  }

  .typing-indicator {
    margin-bottom: 16px;

    .typing-content {
      display: flex;
      align-items: flex-end;
      gap: 8px;

      .typing-avatar {
        .avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
        }
      }

      .typing-bubble {
        background: white;
        padding: 10px 14px;
        border-radius: 18px;

        .typing-dots {
          display: flex;
          gap: 3px;

          span {
            width: 6px;
            height: 6px;
            background: #c0c4cc;
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out;

            &:nth-child(1) {
              animation-delay: -0.32s;
            }

            &:nth-child(2) {
              animation-delay: -0.16s;
            }
          }
        }
      }
    }
  }
}

.input-area {
  border-top: 1px solid #e4e7ed;
  background: white;

  .input-toolbar {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    border-bottom: 1px solid #f0f0f0;

    .upload-btn {
      :deep(.el-upload) {
        display: flex;
        align-items: center;
      }
    }
  }

  .input-container {
    display: flex;
    align-items: flex-end;
    gap: 8px;
    padding: 12px 16px;

    :deep(.el-textarea) {
      flex: 1;

      .el-textarea__inner {
        border: none;
        box-shadow: none;
        resize: none;
        background: transparent;

        &:focus {
          border: none;
          box-shadow: none;
        }
      }
    }

    .send-btn {
      flex-shrink: 0;
    }
  }

  .quick-replies {
    padding: 12px 16px;
    border-top: 1px solid #f0f0f0;
    background: #fafafa;

    h4 {
      margin: 0 0 8px 0;
      font-size: 14px;
      color: #666;
    }

    .reply-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

@media (max-width: 768px) {
  .container {
    height: 100vh;
  }

  .chat-header {
    .contact-info {
      .contact-details {
        h3 {
          font-size: 14px;
        }
      }
    }
  }

  .chat-container {
    padding: 12px;

    .message-item {
      &.own-message .message-bubble {
        margin-left: 40px;
      }

      &.other-message .message-bubble {
        margin-right: 40px;
      }

      .message-bubble {
        max-width: 85%;
      }
    }
  }

  .input-area {
    .input-toolbar {
      padding: 6px 12px;
    }

    .input-container {
      padding: 8px 12px;
    }

    .quick-replies {
      padding: 8px 12px;
    }
  }
}
</style> 